<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>移动小方块</title>
    <style>
        body{
            margin: 0;
            padding: 0;
        }
        #fangkuai{
            width: 50px;
            height: 50px;
            background: blue;

            position: absolute;
            top: 300px;
            left: 100px;
            border-radius: 10px;
        }

    </style>
</head>
<body>

    <div id="fangkuai"></div>

    <script>

        var fangID = document.getElementById('fangkuai');
        var fangstyle = window.getComputedStyle(fangID);

        var fangTop = parseInt(fangstyle.top);
        var fangleft = parseInt(fangstyle.left);

        var tu,td,tl,tr;
        
        var body = document.body;
        body.addEventListener('keydown',function(even){
            
            var key = even.code;
            console.log(key);
            fangTop = parseInt(fangstyle.top);
            fangleft = parseInt(fangstyle.left);
           
            switch(key){
                case 'ArrowUp':
                    ArrowUp();
                    break;
                case 'ArrowDown':
                    ArrowDown()
                    break;
                case 'ArrowLeft':
                    ArrowLeft()
                    break;
                case 'ArrowRight':
                    ArrowRight()    
                    break;
                case 'Space':
                    if(tu != undefined){
                        clearTimeout(tu);
                    }
                    if(td != undefined){
                        clearTimeout(td);
                    }
                    if(tl != undefined){
                        clearTimeout(tl);
                    }
                    if(tr != undefined){
                        clearTimeout(tr);
                    }
                    break;
            }
        })

        function ArrowUp(){
            fangID.style.top = (-- fangTop) + 'px';
           tu =  setTimeout(ArrowUp,5)

           clearTimeout(td)
           clearTimeout(tl)
           clearTimeout(tr)
        }
        function ArrowDown(){
            fangID.style.top = (++ fangTop) + 'px';
           td =  setTimeout(ArrowDown,5)
           clearTimeout(tu)
           clearTimeout(tl)
           clearTimeout(tr)
        }
        function ArrowLeft(){
            fangID.style.left = (-- fangleft) + 'px';
           tl =  setTimeout(ArrowLeft,5)
           clearTimeout(td)
           clearTimeout(tu)
           clearTimeout(tr)
        }
        function ArrowRight(){
            fangID.style.left = (++ fangleft) + 'px';
          tr =   setTimeout(ArrowRight,5)
          clearTimeout(td)
           clearTimeout(tl)
           clearTimeout(tu)
        }




    </script>
    
</body>
</html>